<template>
  <div class="mrp-chart">
    <h2>MRP 计划图表</h2>
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else-if="chartData" class="chart-container">
      <Line :data="chartData" :options="chartOptions" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from 'chart.js';
import { Line } from 'vue-chartjs';

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

// 定义接口类型
interface MRPRequest {
  total_demand: number;
  daily_demand: number;
  order_qty: number;
  reorder_point: number;
  lead_time_days: number;
  start_date: string;
  initial_stock: number;
}

interface OrderInfo {
  序号: number;
  order_date: string;
  arrival_date: string;
  stock_after_arrival: number;
}

interface DailyStockPlan {
  date: string;
  start_stock: number;
  events: string;
}

interface MRPResponse {
  orders_info: OrderInfo[];
  daily_stock_plan: DailyStockPlan[];
}

const props = defineProps<{
  requestData: MRPRequest | null;
}>();

// 导入服务
import { mrpService } from '@/services/mrpService';

const loading = ref(false);
const error = ref<string | null>(null);
const chartData = ref<any>(null);

const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: 'top' as const,
    },
    title: {
      display: true,
      text: 'MRP 计划',
    },
  },
  scales: {
    y: {
      beginAtZero: false,
    },
  },
};

const fetchMRPData = async () => {
  if (!props.requestData) return;

  loading.value = true;
  error.value = null;

  try {
    const response: MRPResponse = await mrpService.calculateMRP(props.requestData);
    
    // 准备图表数据
    const labels = response.daily_stock_plan.map(item => item.date);
    const stockData = response.daily_stock_plan.map(item => item.start_stock);
    
    chartData.value = {
      labels,
      datasets: [
        {
          label: '库存水平',
          data: stockData,
          borderColor: 'rgb(75, 192, 192)',
          backgroundColor: 'rgba(75, 192, 192, 0.2)',
          tension: 0.1,
        },
      ],
    };
  } catch (err) {
    error.value = '获取MRP数据失败';
    console.error(err);
  } finally {
    loading.value = false;
  }
};

watch(() => props.requestData, fetchMRPData, { deep: true });
</script>

<style scoped>
.mrp-chart {
  padding: 20px;
}

.chart-container {
  height: 400px;
  margin-top: 20px;
}

.loading,
.error {
  text-align: center;
  padding: 20px;
  font-size: 18px;
}

.error {
  color: red;
}
</style>